package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.config.AjaxResult;
import com.example.demo.model.UserInfo;
import com.example.demo.service.AuctionService;
import com.example.demo.service.SellerProductService;
import com.example.demo.util.ConstVariable;
import com.example.demo.vo.ProductVO;
import com.example.demo.model.AuctionInfo;
import com.example.demo.model.ProductInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/seller/product")
public class SellerProductController {
    private static final Logger log = LoggerFactory.getLogger(SellerProductController.class);

    @Autowired
    private SellerProductService sellerProductService;

    @Autowired
    private AuctionService auctionService;

    /**
     * 获取卖家商品列表
     */
    @GetMapping("/list")
    public AjaxResult list(@RequestParam(required = false) String status, HttpSession session) {
        try {
            // 验证登录状态
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail(401, "请先登录");
            }

            // 获取商品列表
            List<ProductVO> products = sellerProductService.getProducts(userInfo.getId(), status);
            return AjaxResult.success(products);
        } catch (Exception e) {
            log.error("获取商品列表失败", e);
            return AjaxResult.fail("获取商品列表失败");
        }
    }



    /**
     * 更新商品状态（上架/下架）
     */
    @PostMapping("/update-status")
    public AjaxResult updateStatus(@RequestParam Integer id,
                                 @RequestParam String status,
                                 HttpSession session) {
        try {
            // 验证登录状态
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail(401, "请先登录");
            }

            // 更新商品状态
            boolean success = sellerProductService.updateStatus(id, status, userInfo.getId());
            if (!success) {
                return AjaxResult.fail("操作失败，商品不存在或无权限");
            }
            return AjaxResult.success("操作成功");
        } catch (Exception e) {
            log.error("更新商品状态失败", e);
            return AjaxResult.fail("更新商品状态失败");
        }
    }

    /**
     * 删除商品
     */
    @PostMapping("/delete")
    public AjaxResult delete(@RequestParam Integer id, HttpSession session) {
        try {
            // 验证登录状态
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail(401, "请先登录");
            }

            // 删除商品
            boolean success = sellerProductService.delete(id, userInfo.getId());
            if (!success) {
                return AjaxResult.fail("删除失败，商品不存在或无权限");
            }
            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            log.error("删除商品失败", e);
            return AjaxResult.fail("删除商品失败");
        }
    }

    /**
     * 获取商品详情
     */
    @GetMapping("/detail")
    public AjaxResult detail(@RequestParam Integer id, HttpSession session) {
        try {
            // 验证登录状态
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail(401, "请先登录");
            }

            // 获取商品详情
            ProductVO product = sellerProductService.getProductDetail(id, userInfo.getId());
            if (product == null) {
                return AjaxResult.fail("商品不存在或无权限查看");
            }
            return AjaxResult.success(product);
        } catch (Exception e) {
            log.error("获取商品详情失败", e);
            return AjaxResult.fail("获取商品详情失败");
        }
    }


    /**
     * 更新商品信息
     */
    @PostMapping("/update")
    public AjaxResult updateProduct(@RequestBody ProductInfo product) {
        try {
            // 确保图片数组格式正确
            if (product.getImages() != null) {
                List<String> images = JSON.parseArray(product.getImages(), String.class);
                // 重新序列化以确保格式一致
                product.setImages(JSON.toJSONString(images));
            }
            
            // 更新商品信息
            boolean success = sellerProductService.updateProduct(product);
            if (success) {
                return AjaxResult.success("更新成功");
            } else {
                return AjaxResult.fail("更新失败");
            }
        } catch (Exception e) {
            log.error("更新商品失败", e);
            return AjaxResult.fail("更新失败：" + e.getMessage());
        }
    }

    @PostMapping("/auction/update")
    public AjaxResult updateAuction(@RequestBody AuctionInfo auction) {
        if (auction.getId() == null) {
            return AjaxResult.fail("拍卖ID不能为空");
        }
        
        // 验证必要字段
        if (StringUtils.isEmpty(auction.getProductName())) {
            return AjaxResult.fail("商品名称不能为空");
        }
        if (auction.getStartPrice() == null || auction.getStartPrice().compareTo(BigDecimal.ZERO) <= 0) {
            return AjaxResult.fail("起拍价必须大于0");
        }
        if (auction.getMinIncrement() == null || auction.getMinIncrement().compareTo(BigDecimal.ONE) < 0) {
            return AjaxResult.fail("最小加价必须大于等于1");
        }
        if (auction.getStartTime() == null || auction.getEndTime() == null) {
            return AjaxResult.fail("拍卖时间不能为空");
        }
        if (auction.getStartTime().after(auction.getEndTime())) {
            return AjaxResult.fail("结束时间必须晚于开始时间");
        }
        
        try {
            boolean success = auctionService.updateAuction(auction);
            return success ? AjaxResult.success("更新成功") : AjaxResult.fail("更新失败，拍卖可能已开始或不存在");
        } catch (Exception e) {
            log.error("更新拍卖商品失败", e);
            return AjaxResult.fail("更新失败：" + e.getMessage());
        }
    }
}
